package com.hmdp.MQ;

import cn.hutool.json.JSONUtil;
import com.hmdp.config.RabbitMQTopicConfig;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author zcf
 */
@Slf4j
@Service
public class MQReceiver {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;

    @Resource
    private IVoucherOrderService iVoucherOrderService;

    @RabbitListener(queues = RabbitMQTopicConfig.QUEUE)
    @Transactional
    public void receiveSecKillMessage(String msg) {
        log.info("接收到消息:{}", msg);
        VoucherOrder voucherOrder = JSONUtil.toBean(msg, VoucherOrder.class);
        //拿到优惠券id
        Long voucherId = voucherOrder.getVoucherId();

        //拿到用户id
        Long userId = voucherOrder.getUserId();
        //查询订单保证一人一单
        Integer count = iVoucherOrderService.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if(count>0){
            Result.fail("用户已经购买,一人一单");
        }
        //扣减库存
        boolean b = iSeckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", voucherId).gt("stock",0).update();
        if (!b) {
            log.info("库存不足");
            return;
        }
        //根据消息完成真正下单
        iVoucherOrderService.save(voucherOrder);
    }
}
